import React, { useState, useEffect } from 'react';
import { Table, Space, Button, Input, Modal, Form, message, Tree, Card } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

interface Permission {
  key: string;
  title: string;
  children?: Permission[];
}

interface Role {
  id: string;
  name: string;
  description: string;
  permissions: string[];
}

// 权限树形结构数据
const permissionsData: Permission[] = [
  {
    key: 'user',
    title: '用户管理',
    children: [
      { key: 'user:view', title: '查看用户' },
      { key: 'user:create', title: '创建用户' },
      { key: 'user:edit', title: '编辑用户' },
      { key: 'user:delete', title: '删除用户' },
    ],
  },
  {
    key: 'role',
    title: '角色管理',
    children: [
      { key: 'role:view', title: '查看角色' },
      { key: 'role:create', title: '创建角色' },
      { key: 'role:edit', title: '编辑角色' },
      { key: 'role:delete', title: '删除角色' },
    ],
  },
  {
    key: 'question',
    title: '试题管理',
    children: [
      { key: 'question:view', title: '查看试题' },
      { key: 'question:create', title: '创建试题' },
      { key: 'question:edit', title: '编辑试题' },
      { key: 'question:delete', title: '删除试题' },
    ],
  },
];

const RoleManagement: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      setLoading(true);
      const response = await fetch('/roles');
      const data = await response.json();
      setRoles(data);
    } catch (error) {
      message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRoles();
  }, []);

  // 添加或更新角色
  const handleSubmit = async (values: any) => {
    try {
      const roleData = {
        ...values,
        permissions: selectedPermissions,
      };

      const url = editingId ? `/roles/${editingId}` : '/roles';
      const method = editingId ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(roleData),
      });

      if (response.ok) {
        message.success(`${editingId ? '更新' : '添加'}角色成功`);
        setModalVisible(false);
        form.resetFields();
        setSelectedPermissions([]);
        fetchRoles();
      }
    } catch (error) {
      message.error(`${editingId ? '更新' : '添加'}角色失败`);
    }
  };

  // 删除角色
  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个角色吗？删除后将无法恢复。',
      onOk: async () => {
        try {
          const response = await fetch(`/roles/${id}`, {
            method: 'DELETE',
          });
          
          if (response.ok) {
            message.success('删除角色成功');
            fetchRoles();
          }
        } catch (error) {
          message.error('删除角色失败');
        }
      },
    });
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingId(record.id);
              setSelectedPermissions(record.permissions);
              form.setFieldsValue(record);
              setModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Input
            placeholder="搜索角色"
            prefix={<SearchOutlined />}
            style={{ width: 200 }}
            onChange={(e) => {
              const searchText = e.target.value.toLowerCase();
              const filtered = roles.filter(role => 
                role.name.toLowerCase().includes(searchText) ||
                role.description.toLowerCase().includes(searchText)
              );
              setRoles(filtered);
            }}
          />
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingId(null);
              setSelectedPermissions([]);
              form.resetFields();
              setModalVisible(true);
            }}
          >
            添加角色
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={roles}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title={editingId ? '编辑角色' : '添加角色'}
        open={modalVisible}
        width={720}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
          setSelectedPermissions([]);
        }}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="角色描述"
            rules={[{ required: true, message: '请输入角色描述' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Card title="权限配置" bordered={false}>
            <Tree
              checkable
              checkedKeys={selectedPermissions}
              onCheck={(checkedKeys: any) => {
                setSelectedPermissions(checkedKeys as string[]);
              }}
              treeData={permissionsData}
              defaultExpandAll
            />
          </Card>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement; 